package com.sky.controller.admin;

import com.sky.dto.CountryDTO;
import com.sky.dto.CountryPageQueryDTO;
import com.sky.entity.Country;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CountryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

import java.util.List;

@RestController
@RequestMapping("/admin/country")   // 添加基础路径
@Slf4j
@Api(tags="国家相关接口")
@CrossOrigin
public class CountryController {
    @Autowired
    private CountryService countryService;
    
    @Value("${visa.path.country-images}")
    private String countryImagesPath;

    /**
     * 新增国家
     * @param countryDTO
     * @return
     */
    @PostMapping("/add")   // 修改为具体路径
    @ApiOperation(value = "新增国家")
    public Result<String> insert(@RequestBody CountryDTO countryDTO){
        log.info("新增国家,参数:{}",countryDTO);
        countryService.insert(countryDTO);
        return Result.success();
    }


    /**
     * 启用或禁用国家
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation(value = "启用或禁用国家")
    public Result<String> startOrStop(Long id, @PathVariable Integer status){
        log.info("启用或禁用国家,参数:id:{},status:{}",id,status);
        countryService.startOrStop(id,status);
        return Result.success();
    }

    /**
     * 修改国家
     * @param countryDTO
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改国家")
    public Result<String> update(@RequestBody CountryDTO countryDTO){
        log.info("修改国家,参数:{}",countryDTO);
        countryService.update(countryDTO);
        return Result.success();
    }

    /**
     * 删除国家
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "删除国家")
    public Result<String> delete(Long id){
        log.info("删除国家,参数:{}",id);
        countryService.delete(id);
        return Result.success();
    }

    /**
     * 分页查询国家
     * @param countryPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询国家")
    public Result<PageResult> page(CountryPageQueryDTO countryPageQueryDTO){
        log.info("查询国家列表,参数:{}",countryPageQueryDTO);
        PageResult pageResult = countryService.page(countryPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 查询和该国家关联的签证产品数量
     * @param id
     * @return
     */
    @GetMapping("/count/{id}")
    @ApiOperation("查询和该国家关联的签证产品数量")
    public Result<Integer> countProductNumber(@PathVariable Long id){
        log.info("查询和该国家关联的签证产品数量,参数:{}",id);
        Integer count = countryService.countProductNumber(id);
        return Result.success(count);
    }

    @Value("${visa.path.image-base-url}")
    private String imageBaseUrl;
    @GetMapping("/public/list")
    @ApiOperation("获取国家列表(公开接口)")
    public Result<List<Map<String, Object>>> publicList() {
        List<Country> list = countryService.list();
        List<Map<String, Object>> result = list.stream().map(country -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name", country.getCountryName());
            map.put("name1", country.getCountryEnglishName());
            map.put("continent", country.getContinent());
            map.put("price", country.getProductNumber());
            String imageUrl = country.getImageUrl();
            if (imageUrl != null && !imageUrl.startsWith("http")) {
                imageUrl = imageBaseUrl + imageUrl;
            }
            map.put("image", imageUrl);
            map.put("id", country.getId());
            map.put("status", country.getStatus());
            map.put("createTime", country.getCreateTime());
            return map;
        }).collect(Collectors.toList());
        return Result.success(result);
    }
    // 修改上传图片的路径，避免冲突
    @PostMapping("/upload")  // 改为更具体的路径
    @ApiOperation("上传国家图片")
    public Result<String> uploadImage(@RequestPart("file") MultipartFile file) {
        log.info("上传国家图片：{}", file);
        
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            
            File dir = new File(countryImagesPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            file.transferTo(new File(countryImagesPath + fileName));
            
            String fileUrl = "/images/country/" + fileName;
            return Result.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            return Result.error("文件上传失败");
        }
    }
}
